# -*- coding:utf-8 -*-
import uuid
from datetime import datetime

import torndb

import setting

from util.wechatpy.message import WeChatMessageTpl


class TmpGiftMessageNotice(object):
    """
    导入20周年礼品给用户

    """

    def __init__(self):

        self.db = torndb.Connection(
            host=setting.mysql_host,
            database=setting.mysql_database,
            user=setting.mysql_user,
            password=setting.mysql_password,
            charset='utf8mb4'
        )

        self.access_token = ""

        self.tpl = WeChatMessageTpl()


    def _get_create_tmp_user(self):
        """
        获取获奖人的openid和对应的礼物（商品ID）

        :return:
        """
        return self.db.query("select openid from tmp_user group by openid")

    def _get_product(self, openid):
        return self.db.query("select product_id from tmp_user where openid=%(openid)s", openid=openid)

    def _get_user_id(self, openid):
        """
        校验该商品名称是否存在，防止重复导入

        :param product_name: 商品名称
        :return:
        """
        return self.db.get("select user_id from t_wechat where openid=%(openid)s", openid=openid)

    def _create_order(self, openid):
        """
        将商品插入t_product


        insert into t_order (id, user_id, total_fee, paytime, status, create_date, update_date, out_trade_no) values ("8bc5f5c30a0043699046845d2f605d1f", "67f2fe76d8b845ccbe7ebae6a4ead405", 1190000, now(), 1, now(), now(), "1");
        insert into r_order_product (id, order_id, product_id, cnt, source) values("7f0b26bede0c475082d8483379310b49", "8bc5f5c30a0043699046845d2f605d1f", "120", 8, 0);
        :param params:
        :return:
        """
        # product = self.db.get("select * from t_product where id=%(product_id)s", product_id=product_id)

        user = self._get_user_id(openid)

        order_id = str(uuid.uuid4()).replace("-", "")
        out_trade_no = str(uuid.uuid4()).replace("-", "")
        self.db.execute(
            "insert into t_order (id, user_id, total_fee, paytime,status,create_date,update_date, out_trade_no) "
            "values (%(order_id)s, %(user_id)s, %(total_fee)s, now(),1,now(),now(), %(out_trade_no)s)",
            order_id=order_id, user_id=user.user_id, out_trade_no=out_trade_no, total_fee=0)

        products = self._get_product(openid)
        for p in products:
            order_product_id = str(uuid.uuid4()).replace("-", "")
            self.db.execute("insert into r_order_product (id, order_id, product_id, cnt, source) "
                            "values (%(order_product_id)s, %(order_id)s, %(product_id)s, 1, 0)",
                            order_product_id=order_product_id, order_id=order_id, product_id=p.product_id)

            print "order_id:{}, order_product_id:{}".format(order_id, order_product_id)

            #
            product = self.db.get("select title from t_product where id = %(product_id)s", product_id=p.product_id)

            # send notice
            self.tpl.activity_result_notice(openid, product.title)


    def runner(self):

        users = self._get_create_tmp_user()
        for u in users:
            self._create_order(u.openid)

if __name__ == '__main__':
    print "run start : {}".format(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
    tgn = TmpGiftMessageNotice()
    tgn.runner()
    tgn.db.close()
    print "run end : {}".format(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))


